import XLSX from "xlsx"

const commonFun = {
    file2Xce: function (file) {
        let that = this
        return new Promise((resolve, reject) => {
            const reader = new FileReader()
            reader.onload = e => {
                const data = e.target.result
                that.wb = XLSX.read(data, {
                    type: 'binary'
                })
                const result = []
                that.wb.SheetNames.forEach((sheetName) => {
                    result.push({
                        sheetName: sheetName,
                        sheet: XLSX.utils.sheet_to_json(that.wb.Sheets[sheetName])
                    })
                })
                resolve(result)

            }
            reader.readAsBinaryString(file)
        })
    },
    // getExcel(tHeader, filterVal, name,sheetName, res) {
    //     require.ensure([], () => {
    //         const { export_json_to_excel } = require('./Export2Excel-bk.js/index.js.js')
    //         const list = res
    //         const data = this.formatJson(filterVal, list)
    //         export_json_to_excel(tHeader, data,sheetName, name)
    //     })
    // },

    // formatJson(filterVal, jsonData) {

    //     return jsonData.map(v => filterVal.map(j => v[j]))
    // },
    // tableJson 导出数据 ; filenames导出表的名字; autowidth表格宽度自动 true or false; bookTypes xlsx & csv & txt
    json2excel (tableJson, filenames, autowidth, bookTypes) {
        var that = this
  //这个是引用插件
        import("./Export2Excel").then(excel => {
          var tHeader = []
          var dataArr = []
          var sheetnames = []
          for (var i in tableJson) {
            tHeader.push(tableJson[i].tHeader)
            dataArr.push(that.formatJson(tableJson[i].filterVal, tableJson[i].tableDatas))
            sheetnames.push(tableJson[i].sheetName)
          }
          excel.export_json_to_excel({
            header: tHeader,
            data: dataArr,
            sheetname: sheetnames,
            filename: filenames,
            autoWidth: autowidth,
            bookType: bookTypes
          })
        })
      },
      // 数据过滤，时间过滤
      formatJson (filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
}



export default commonFun